package org.cyz.tools.controller;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.jfoenix.controls.*;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Orientation;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.stage.Modality;
import org.cyz.tools.common.bean.Settings;
import org.cyz.tools.common.dto.FeedbackDTO;
import org.cyz.tools.common.util.*;
import org.cyz.tools.core.assembly.Notify;
import org.cyz.tools.core.assembly.dialog.DialogBuilder;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.ResourceBundle;

public class FloatMenuController implements Initializable {

    @FXML
    JFXNodesList nodesList;

    @FXML
    JFXButton settings;
    @FXML
    JFXButton share;
    @FXML
    JFXButton feedback;
    @FXML
    JFXButton menu;

    //是否自动更新
    private JFXToggleButton updateButton=new JFXToggleButton();
    //打开key是否复制到剪贴板
    private JFXToggleButton clipButton=new JFXToggleButton();
    //每次加载key的数量
    private  JFXSlider loadKeySlider = new JFXSlider();

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        //初始化监听
        initListener();
        //初始化数据
        initData();
    }


    private void initListener() {
        updateButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                InitDataUtil.setUpdate(InitDataUtil.UPDATE, String.valueOf(updateButton.isSelected()));
                if(updateButton.isSelected()){
                    UpdateUtil.checkUpdate();
                }
            }
        });
        clipButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                InitDataUtil.setUpdate(InitDataUtil.CLIP, String.valueOf(clipButton.isSelected()));
            }
        });
        loadKeySlider.setOnMouseReleased(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                InitDataUtil.setUpdate(InitDataUtil.LOAD_KEY, String.valueOf(loadKeySlider.getValue()));
                //更新获取key的数量
                TreeUtil.reloadKewCount();
            }
        });
    }

    private void initData() {
        settings.setTooltip(new Tooltip("系统设置"));
        //share.setTooltip(new Tooltip("应用分享"));
        feedback.setTooltip(new Tooltip("问题反馈"));
        menu.setTooltip(new Tooltip("配置"));
        Tooltip tooltip=new Tooltip();
        byte[] img= QRCodeUtil.getQRCodeImage(CommonUtil.UPDATE_URL,200,200);
        Image image=new Image(new ByteArrayInputStream(img));
        tooltip.setGraphic(new ImageView(image));
        share.setTooltip(tooltip);

        loadKeySlider.setMax(10000);
        loadKeySlider.setMin(500);

        //设置界面参数
        Settings updateBean= InitDataUtil.getSettings(InitDataUtil.UPDATE);
        if(null!=updateBean){
            updateButton.setSelected(Boolean.valueOf(updateBean.getValue()));
        }
        Settings clipBean= InitDataUtil.getSettings(InitDataUtil.CLIP);
        if(null!=clipBean){
            clipButton.setSelected(Boolean.valueOf(clipBean.getValue()));
        }
        Settings loadBean= InitDataUtil.getSettings(InitDataUtil.LOAD_KEY);
        if(null!=loadBean){
            loadKeySlider.setValue(Integer.valueOf(loadBean.getValue().split("\\.")[0]));
        }
    }


    /**
     * 系统设置
     */
    public void onSettings() {
        JFXAlert alert = new JFXAlert(settings.getScene().getWindow());
        alert.initModality(Modality.APPLICATION_MODAL);
        alert.setOverlayClose(false);
        JFXDialogLayout layout = new JFXDialogLayout();
        layout.setHeading(new Label("系统设置"));
//        layout.setStyle("-fx-background-color:#EEE; -fx-padding: 40;");

        FlowPane flowPane=new FlowPane();
        //设置布局方向
        flowPane.setOrientation(Orientation.VERTICAL);

        //是否自动更新
        updateButton.setText("自动更新");
        updateButton.setStyle("'styleClass=custom-jfx-toggle-button'");
        flowPane.getChildren().add(updateButton);

        //打开key是否复制到剪贴板
        clipButton.setText("复制选中key的值");
        clipButton.setStyle("'styleClass=custom-jfx-toggle-button'");
        flowPane.getChildren().add(clipButton);

        //每次加载key的数量
        loadKeySlider.setMinHeight(30);
        loadKeySlider.setOrientation(Orientation.HORIZONTAL);
        loadKeySlider.setTooltip(new Tooltip("加载Key的数量: "+String.valueOf(loadKeySlider.getValue()).split("\\.")[0]));
        flowPane.getChildren().add(loadKeySlider);


//        Version version=UpdateUtil.getRemoteVersion("");
//        Label lName=new Label("当前版本: "+PomUtil.getVersion() +"(远程版本: "+version.getVersion()+")");
//        lName.setFont(new Font(11));
//        flowPane.getChildren().add(lName);

        layout.setBody(flowPane);
        JFXButton closeButton = new JFXButton();
        closeButton.setText("关闭");
        closeButton.getStyleClass().add("dialog-accept");
        closeButton.setOnAction(event -> alert.hideWithAnimation());
        layout.setActions(closeButton);
        alert.setContent(layout);
        alert.show();
        nodesList.animateList(false);
    }

    /**
     * 问题反馈
     */
    public void onFeedBack() {
        nodesList.animateList(false);
        new DialogBuilder(feedback)
                .setWrap(true)
                .setMultiLine(200,70)
                .setTitle("反馈")
                .setPromptText("请留下您宝贵建议或意见!")
                .setMessage("问题/建议")
                .setTextFieldText(new DialogBuilder.OnInputListener() {
            @Override
            public void onGetText(String result) {
                Platform.runLater(()->{
                    FeedbackDTO feedbackDTO=new FeedbackDTO();
                    feedbackDTO.setContent(result);
                    feedbackDTO.setCreateTime(System.currentTimeMillis());
                    feedbackDTO.setMac(MacUtil.getLocalMac());
                    feedbackDTO.setUserId(-1);
                    feedbackDTO.setUserName("default");
                    String _r= HttpRequest.post(UpdateUtil.FEED_BACK_URL)
                            .setConnectionTimeout(2000)
                            .setReadTimeout(2000)
//                            .body(JSON.toJSONString(feedbackDTO),"application/json")
                            .body(JSON.toJSONString(feedbackDTO))
                            .execute().body();
                    System.out.println(_r);
                });
            }
        }).setPositiveBtn("确定").setNegativeBtn("取消").create();

    }

    /**
     * 分享
     */
    public void onShare() {
        //设置url到剪贴板
        KeyBoardUtil.setClipboard(CommonUtil.UPDATE_URL,0);
        Notify.toast("分享链接已复制到剪贴板!");
    }


}
